﻿

$(function () {
    // 重置窗口大小
    function resizeWindow() {
        var DEBUG;
        //DEBUG = true;
        if (DEBUG) {
            [].forEach.call($($('*')), function (a) {
                a.style.outline = '1px solid #' + (~~(Math.random() * (1 << 24))).toString(16);
            });
        }
        //console.log('resize...');
        var minHeight = $(window).height() - $('#dataTreeDiv').offset().top - 20;
        $('#dataTreeDiv').css('max-height', minHeight);
        $('.leftDiv').height($(window).height() - $('.leftDiv').offset().top - 20);
    }
    resizeWindow();
    // resize窗口
    window.onresize = function () {
        resizeWindow();
    };
    var portaluserno = getCookie ('portaluserno')
    var configInfo=InitialParameter("/Config.json")
    var modelApi = getBaseplatformPort () 
    // 根节点id(自定义)
    var rootNodeId = '101010';
    // 当前节点id
    var nowNodeId = '';
    // 当前节点对象
    var nowNode;
    // 当前页码
    var nowPage = 1;
    //初始化
    getUserInfo_SH(nowNodeId);
    //列表显示
    function getUserInfo_SH(nowNodeId, page, isSecond) {
        $('#userTable').html('');
        // 返回的数据 
        var data = {
            hasTotal: 1,
            pageNum: page || 1, // 请求页码: 1,2,3…
            perPageNum: 5, // 每页条数: 1,2,3…
            mtype: "UserManage_GetUserInfoByNames_SH",
            userName: $('#searchUserName').val(),
            name: $('#searchName').val(),
            state: $('input[name="Audit"]:checked').val(),
            organizationId: nowNodeId,
        };
        //if (states == 'search') {
            
        //    if (nowNodeId == "") {
        //        $.extend(data, {
        //            mtype: "UserManage_GetUserInfoByNames_SH",
        //            userName: $('#searchUserName').val(),
        //            name: $('#searchName').val(),
        //            state: $('input[name="Audit"]:checked').val(),
        //            organizationId: nowNodeId,
        //        });
        //    } 
        //}
        //else {
        //    $.extend(data, {
        //        mtype: "UserManage_GetUserInfoByOrgID_SH",
        //        organizationId: nowNodeId || '',
        //    });
        //}
        getData (isSecond)  
        checkall();
    }
    $('.searchBtn').on('click', function () {
        getData('searchBtnSH');
    });
    function getData (isSecond,newNowNodeId) {
        let data 
        if (isSecond == 'searchBtnSH') {
            data = {
                userName: $('#searchUserName').val(), 
                name: $('#searchName').val(),
                orgId:nowNodeId,
                // status:document.getElementById("isManagerInput").checked ? 1 : 2 
                status:$("input[name='Audit']").prop("checked") ? 1 : 2 
            }
        } else if (isSecond == 'btnSearch') {
            data = {
                userName: $('#searchUserName').val(), 
                name: $('#searchName').val(),
                orgId:nowNodeId == '' ? 101010 : nowNodeId ,
                // status:$("input[name='Audit']").prop("checked") ? 0 : 2   // 待审核 0  审核未通过 2 都不选传空
                status: $("input[name='Audit']:checked").attr("id") === 'Audit0' ? 0 : $("input[name='Audit']:checked").attr("id") === 'Audit1' ? 2 : ''
            }
        } else {
            data = { 
                fkDept: nowNodeId == '' ? 101010 : nowNodeId  
            }
        }
        $.ajax({
            type: "post",
            async: false,
            // url: "/BaseAshx/User/UserManage.ashx",
            // data: data,
            url:modelApi + 'user/getUserInfoByNamesSH',
            data:data,
            datatype: "json",
            success: function (result) {
                result = JSON.parse(result);
                if (result.code == 200) {
                    if (!result.data) {
                        $('#userTable').html('<div style="height: 100px;line-height:100px;text-align: center;font-size: xx-large;color: #666;">无数据</div>');
                        $('#pagination').html('');
                        return;
                    }
                    //console.log(result);
                    var html = "<tbody>" +
                    "<tr class='head' align='center'>" +
                            "<th><input type='checkbox' id='all' title='全选' /></th>" +
                            "<th>用户名</th>" +
                            "<th>中文名</th>" +
                            "<th>所在部门</th>" +
                            "<th>职务</th>" +
                            "<th>手机号</th>" +
                            "<th>邮箱</th>" +
                            "<th>状态</th>" +
                        "</tr>";
                    result.data.map(function (item, index) {
                        var zhuangtai = item.STATE;
                        var state;
                        if (zhuangtai == "0") {
                            state = "待审核";
                        } else if (zhuangtai == "1") {
                            state = "审核通过";
                        } else {
                            state = "审核未通过";
                        }
                        html += '<tr userid="' + item.USERID + '" align = "center">' +
                            '<td><input userid="' + item.USERID + '" user="' + item.USERNAME + '" type="checkbox" name="ck_box" /></td>' +
                        '<td>' + item.USERNAME + '</td>' +
                        ' <td>' + item.NAME + '</td>' +
                        '<td>' + item.DEPT + '</td>' +
                        '<td departmentId="' + item.DEPARTMENTID + '">' + item.DEPARTMENTID + '</td>' +
                        '<td>' + item.PHONE + '</td>' +
                        ' <td>' + item.MAIL + '</td>' +
                        '<td >' + state + '</td>'
                    });
                    html += '</tbody>';
                    $('#userTable').html(html);
                    var data = {
                        pageTotal: Math.ceil(result.data.total / 5),
                        pageAmount: 5, // 每页多少条
                        dataTotal: result.data.total,
                        curPage: 1
                    };
                    if (isSecond) {
                        return;
                    };
                    new Page({
                        id: 'pagination',
                        pageTotal: data.pageTotal, //必填,总页数（最少1页）
                        pageAmount: data.pageAmount, //每页多少条
                        dataTotal: data.dataTotal, //总共多少条数据（至少1条）
                        curPage: data.curPage, //初始页码,不填默认为1
                        pageSize: data.pageSize, //分页个数,不填默认为5
                        showPageTotalFlag: true, //是否显示数据统计,不填默认不显示
                        showSkipInputFlag: true, //是否支持跳转,不填默认不显示
                        getPage: function (page) {
                            nowPage = page;
                            // 请求数据
                            //if (states == 'search') {
                            //    getUserInfo_SH('search', nowNodeId,page, true);
                            //} else {
                               getUserInfo_SH(nowNodeId, page, true);
                            //}

                        }
                    });
                    nowPage = 1;
                } else {
                    layui.layer.msg(result.msg, {
                        shade: 0.3,
                        time: 1000 // 1秒关闭
                    });
                    return;
                }
            },
            error: function (error) {
                console.log(error);
            }
        });
    }
    //radio第一次点击选中，再次点击取消选中
    $('input[name="Audit"]').click(function () {
        var $radio = $(this);
        if ($radio.data('checked')) {
            $radio.prop('checked', false);
            $radio.data('checked', false);
        } else {
            $radio.prop('checked', true);
            $radio.data('checked', true);
        }
        

    })
    
    //全选或者全不选
    function checkall() {
        var ck_box = document.getElementsByName('ck_box');
        $('#all').on('click', function () {
            if (this.checked) {
                for (var j = 0; j < ck_box.length; j++) {
                    //全选
                    ck_box[j].checked = true;

                }
            } else {
                //var ck_box = document.getElementsByName('ck_box');
                for (var j = 0; j < ck_box.length; j++) {
                    //全不选
                    ck_box[j].checked = false;


                }
            }
        })

    }
    
 
    
    //通过
    $('#adopt').on('click', function () {
        var i = $('input[name="ck_box"]:checked');
        var user = "";
        if (i.length == 0) {
            layui.layer.msg('至少选择一个用户', {
                shade: 0.3,
                time: 1000 // 1秒关闭
            });
            return;
        } else {
            i.each(function (index, item) {
                console.log($(item).attr('user'))
                user += $(item).attr('user') + ",";
            })
            user = user.substr(0, user.length - 1);
            var mtype = 1;
            var content = '<div>\n' +
                '<a id="check">是否通过"' + user + '"用户注册信息么？</a>\n' +
                '</div>';
            layer.open({
                id: 3,
                type: 1,
                title: '通过用户信息',
                skin: 'layui-layer-prompt',
                content: content,
                btn: ['确定', '取消'],
                area: ['300px', '160px'],
                shadeClose: true, //点击遮罩关闭
                btn2: function (index, layero) {
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    layer.close(index);
                    state(mtype);
                    //getUserInfo_SH(nowNodeId);
                }

            })
        }
    })
    //未通过
    $('#noadopt').on('click', function () {
        var i = $('input[name="ck_box"]:checked');
        var user = "";
        if (i.length == 0) {
            layui.layer.msg('至少选择一个用户', {
                shade: 0.3,
                time: 1000 // 1秒关闭
            });
            return;
        } else {

            i.each(function (index, item) {
                console.log($(item).attr('user'))
                user += $(item).attr('user') + ",";
            })
            user = user.substr(0, user.length - 1);
            var mtype = 2;
            var content = '<div>\n' +
                '<a id="check">是否未通过"' + user + '"用户注册信息么？</a>\n' +
                '</div>';
            layer.open({
                id: 3,
                type: 1,
                title: '未通过用户信息',
                skin: 'layui-layer-prompt',
                content: content,
                btn: ['确定', '取消'],
                area: ['300px', '160px'],
                shadeClose: true, //点击遮罩关闭
                btn2: function (index, layero) {
                    layer.close(index);
                },
                btn1: function (index, layero) {
                    layer.close(index);
                    state(mtype)
                   // getUserInfo_SH(nowNodeId);
                }
            })
        }
    })
    //搜索
    $('#btn_search').on('click', function () {
        checkall();
        getUserInfo_SH(nowNode,'','btnSearch');
        // getData ()
    }); 
    function state(mtype)
    {
        var ids = "";
        var comma = ',';
        var i = $('input[name="ck_box"]:checked');
            i.each(function (index, item) {
                console.log($(item).attr('userid'))
                if (i.length == 1) {
                    ids += $(item).attr('userid') + ",";

                } else {
                    ids += $(item).attr('userid') + comma;
                }
            })
            // if (i.length == 1) {
            //     ids = ids.substr(0, ids.length - 1);
            // } else {
            //     ids = ids.substr(0, ids.length - 3);
            // }
            $.ajax({
                type: 'post',
                async: false,
                // url: '/BaseAshx/User/UserManage.ashx',
                // data: {
                //     mtype: mtype,
                //     id: ids
                // },
                url: modelApi + 'user/UserSH', // 点击通过 审核用户 的接口
                data: {
                    status: mtype,
                    ids: ids
                },
                success: function (result) {
                    result = JSON.parse(result);
                    if (result.code == 200) {
                        getData () 
                        layui.layer.msg(result.msg, {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        
                    } else {
                        layui.layer.msg(result.msg, {
                            shade: 0.3,
                            time: 1000 // 1秒关闭
                        });
                        return;
                    }
                }
            })
        
    }


    var settingLeft = {
        view: {
            dblClickExpand: false, //双击节点时，是否自动展开父节点的标识
            showLine: false, //是否显示节点之间的连线
            showIcon: true,
            fontCss: {
                'color': 'white',
                'font-weight': 'normal'
            }, //字体样式函数
            selectedMulti: false //设置是否允许同时选中多个节点
        },
        check: {
            //chkboxType: { "Y": "ps", "N": "ps" },
            chkStyle: "checkbox", //复选框类型
            enable: false //每个节点上是否显示 CheckBox
        },
        data: {
            simpleData: { //简单数据模式
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            onClick: function (event, treeId, treeNode) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left");
                if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                    zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                }
                var text = $(event.target).text();
                // console.log(treeNode);
                if (text) {
                    $('#orgInput').attr('checkId', treeNode.id);
                    $('#orgInput').val(text);
                    $('#ztreeDiv').hide();
                }
            },
        }
    };

    // 获取左侧机构组织数据
    var zNodes;
    // 获取机构上下级树
    var orgData = [];
    $.ajax({
        type: "post",
        async: false,
        // url: "/BaseAshx/Org/OrgAshx.ashx",
        // data: {
        //     stype: 'OrgManage_QueryOrgTree',
        //     orgid: rootNodeId,
        //     treetype: 'down'
        // }, 
        url:modelApi + 'dept/getAllDepts',
        data: {
            orgid: rootNodeId,
            treetype: 'down'
        },
        datatype: "json",
        success: function (result) {
            // console.log(result);
            result = JSON.parse(result);
            if (result.code == 200) {
                var data = result.data;
                zNodes = data.map(function (item, index) {
                    // console.log(item);
                    var mapResult = {
                        "id": item.ORG_ID,
                        "name": item.ORGSHORTNAME,
                        "pId": item.ORG_PID,
                    };
                    if (index == 0) {
                        mapResult.open = true;
                    }
                    return mapResult;
                });
                //初始化菜单树
                $.fn.zTree.init($("#menu_tree_left"), settingLeft, zNodes);
                // 点击第一个节点,获取右侧数据
                // setTimeout(function () {
                //     $('#menu_tree_left2 a').eq(0).click();
                // }, 100);
            } else {
                layui.layer.msg('获取机构数据错误,请稍候再试', {
                    shade: 0.3,
                    time: 1000 // 1秒关闭
                });
            }
        },
        error: function (error) {
            console.log(error);
        }
    });

    var settingLeft2 = {
        view: {
            showTitle: false,
            dblClickExpand: false, //双击节点时，是否自动展开父节点的标识
            showLine: false, //是否显示节点之间的连线
            showIcon: true,
            fontCss: {
                'color': 'white',
                'font-weight': 'normal'
            }, //字体样式函数
            selectedMulti: false //设置是否允许同时选中多个节点
        },
        check: {
            //chkboxType: { "Y": "ps", "N": "ps" },
            chkStyle: "checkbox", //复选框类型
            enable: false //每个节点上是否显示 CheckBox
        },
        data: {
            simpleData: { //简单数据模式
                enable: true,
                idKey: "id",
                pIdKey: "pId",
                rootPId: ""
            }
        },
        callback: {
            beforeClick: function (treeId, treeNode) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left");
                // if (!treeNode.isParent) {
                //     zTree.checkNode(treeNode, !treeNode.checked, true, true); //单击勾选，再次单击取消勾选
                // }

                // if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                //     zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                // }
            },

            onClick: function (event, treeId, treeNode, e) {
                zTree = $.fn.zTree.getZTreeObj("menu_tree_left2");
                if ($(event.target).hasClass('ico_close') || $(event.target).hasClass('ico_open')) {
                    zTree.expandNode(treeNode); //如果是父节点，则展开该节点
                }
                var text = $(event.target).text();
                console.log(treeNode);
                // 获取右侧对应用户数据
                nowNodeId = treeNode.id;
                nowNode = treeNode;
                $('#pagination').html('');
                getUserInfo_SH(nowNodeId);
                // if (text) {
                //     $('#orgInput').val(text);
                //     $('#ztreeDiv').hide();
                // }
            },
            onDblClick: function (treeId, treeNode) {
                //code
            }
        }
    };
    $.fn.zTree.init($("#menu_tree_left2"), settingLeft2, zNodes);
})